package cn.huolabao.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.huolabao.dao.SysDeptMapper;
import cn.huolabao.model.SysDept;
import cn.huolabao.service.SysDeptService;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public Page<SysDept> selectDeptList(Page<SysDept> sysDeptPage, SysDept sysDept) {
        return this.baseMapper.selectDeptList(sysDeptPage, sysDept);
    }

    @Override
    public List<SysDept> getTree() {
        List<SysDept> allDept = this.list();
        List<SysDept> rootDept = new ArrayList<>();
        for (SysDept dept : allDept) {
            if (dept.getParentId() == 0) {
                rootDept.add(dept);
            }
        }
        for (SysDept menu : rootDept) {
            List<SysDept> child = getChild(menu.getId(), allDept);
            menu.setChildren(child);
        }
        return rootDept;
    }

    private List<SysDept> getChild(Integer id, List<SysDept> all) {
        List<SysDept> childMenu = new ArrayList<>();

        for (SysDept dept : all) {
            if (dept.getParentId().equals(id)) {
                childMenu.add(dept);
            }
        }

        for (SysDept dept : childMenu) {
            dept.setChildren(getChild(dept.getId(), all));
        }

        if (childMenu.size() == 0) {
            return new ArrayList<>();
        }
        return childMenu;
    }
}
